<?php


namespace app\im\Router;


use app\im\Router\impl\routers;

class checkRule
{
    protected array $routers = [];

    protected string $routerKey = 'action';

    public function __construct()
    {
        $this->routers = app(routers::class) -> getRouters();
    }

    public function check(string $event, mixed $data)
    {
        $routers = $this->routers[$event] ?? [];
        if (!$routers) return false;
        if (empty($data[$this -> routerKey])) return false;

        $actionArr = explode('/', $data[$this -> routerKey]);
        $actionArrLength = count($actionArr);
        return $this->checkRule($routers, $actionArr, $actionArrLength);
    }


    protected function checkRule(
        array $routers,
        array $actionArr,
        int $actionArrLength
    ) {
        $router = '';
        foreach ($routers as $actionKey => $routerAction) {
            if ($actionArrLength > 1 && !is_numeric($actionKey)) {
                $actionKeyLength = count(explode('/', $actionKey));
                if ($actionKeyLength === $actionArrLength - 1) {
                    // 获取分组路由
                    $router = $this->checkRule($routerAction, [
                        $actionArr[$actionKeyLength]
                    ], $actionArrLength - $actionKeyLength);
                    if ($router) break;
                }
            }
            if (str_ends_with($routerAction, $actionArr[0]) && $actionArrLength === 1) {
                // 验证是否与方法相同
                $router = $routerAction;
                break;
            }

            if ($actionArr[0] === $actionKey && $actionArrLength === 1) {
                // 验证是否与 KEY 相同
                $router = $routerAction;
                break;
            }
        }

        if ($router !== '') {
            [$class, $action] = explode('@', $router);
            if ($action === '*') {
                $router = "{$class}@{$actionArr[0]}";
            }
        }

        return $router;
    }
}